#include "bsp_sdhi.h"
#include "common_utils.h"
#include "common_data.h"
#include "ff.h"
#include "diskio.h"

MKFS_PARM f_opt =
{
    .fmt = FM_FAT32,  //格式选项
    .n_fat = 0,     //FATs大小
    .align = 0,     //数据区域对齐（扇区）
    .n_root = 0,    //根目录条目数
    .au_size = 0,   //群集大小（字节）
};
/* FatFs文件系统对象 */
FATFS fs;
/* 文件对象 */
FIL fnew;
/* 文件成功读写数量 */
UINT fnum;
/* 文件操作结果 */
FRESULT res_sd;
/* 读缓冲区 */
BYTE ReadBuffer[1024]= {0};
/* 写缓冲区*/
BYTE WriteBuffer[] = "RA8D1 DEMO板FATFS挂载SD卡测试程序";
BYTE work[FF_MAX_SS];


__IO uint32_t g_transfer_complete = 0;
__IO uint32_t g_card_erase_complete = 0;
__IO bool g_card_inserted = false;

sdmmc_device_t my_sdmmc_device = {0};

/* SDHI SD卡初始化函数 */
void SDCard_Init(void)
{
    fsp_err_t err;

    /* 打开SDHI */
    err = R_SDHI_Open(&g_sdmmc1_ctrl, &g_sdmmc1_cfg);
    assert(FSP_SUCCESS == err);
}

void SDCard_DeInit(void)
{
    fsp_err_t err;

    /* 关闭SDHI */
    err = R_SDHI_Close(&g_sdmmc1_ctrl);
    assert(FSP_SUCCESS == err);
}

void g_sdmmc1_callback(sdmmc_callback_args_t *p_args)
{
    if (SDMMC_EVENT_TRANSFER_COMPLETE == p_args->event)  //读取或写入完成
    {
        g_transfer_complete = 1;
    }

    if (SDMMC_EVENT_CARD_INSERTED == p_args->event)  //卡插入中断
    {
        g_card_inserted = true;
    }

    if (SDMMC_EVENT_CARD_REMOVED == p_args->event)   //卡拔出中断
    {
        g_card_inserted = false;
    }

    if (SDMMC_EVENT_ERASE_COMPLETE == p_args->event)  //擦除完成
    {
        g_card_erase_complete = 1;
    }

    if (SDMMC_EVENT_ERASE_BUSY == p_args->event)  //擦除超时
    {
        g_card_erase_complete = 2;
    }
}

void SDHI_RW_Test(void)
{
    uint8_t buf[512]= {0};
    /*----------------------- 格式化测试 ---------------------------*/
    /* 尝试挂载外部FLASH FAT文件系统 */
    res_sd = f_mount(&fs, "0:", 1);

    /* 如果没有文件系统就格式化SD卡创建文件系统 */
    if(res_sd == FR_NO_FILESYSTEM)
    {
        APP_PRINT("The SD card doesn't have a file system yet; it's about to be formatted....\r\n");
        /* 格式化 */
        res_sd = f_mkfs("0:", NULL, work, sizeof(work));

        if(res_sd == FR_OK)
        {
            APP_PRINT("The SD card has been successfully formatted with a file system.\r\n");
            /* 格式化后，先取消挂载 */
            res_sd = f_mount(NULL, "0:", 1);
            /* 重新挂载   */
            res_sd = f_mount(&fs, "0:", 1);
        }
        else
        {
            APP_PRINT("Formatting failed.\r\n");
        }
    }
    else if(res_sd != FR_OK)
    {
        APP_PRINT("Failed to mount the file system on the SD card.(%d)\r\n", res_sd);
    }
    else
    {
        APP_PRINT("File system mounted successfully; proceeding with read/write test.\r\n");
    }

    /*----------------------- 文件系统测试：写测试 -----------------------------*/
    /* 打开文件，如果文件不存在则创建它 */
    APP_PRINT("\r\n****** About to perform file write test... ******\r\n");
    // 创建新文件。如果该文件存在，则覆盖。  |
    // 可以写文件
    res_sd = f_open(&fnew, "0:FatFs Read Write Test.txt", FA_CREATE_ALWAYS | FA_WRITE);  //FatFs读写测试文件 FatFs_files

    if ( res_sd == FR_OK )
    {
        APP_PRINT("Successfully opened/created the FatFs read-write test file \"test.txt\"; writing data to the file.\r\n");
        /* 将指定存储区内容写入到文件内 */
        res_sd = f_write(&fnew, WriteBuffer, sizeof(WriteBuffer), &fnum);

        if(res_sd == FR_OK)
        {
            APP_PRINT("File write successful, bytes written:%d\n", fnum);
            APP_PRINT("Data written to the file:\r\n%s\r\n", WriteBuffer);
        }
        else
        {
            APP_PRINT("File write failed:(%d)\n", res_sd);
        }

        /* 不再写，关闭文件 */
        f_close(&fnew);
    }
    else
    {
        APP_PRINT("Failed to open/create file.\r\n");
    }

    /*------------------- 文件系统测试：读测试 ------------------------------------*/
    APP_PRINT("\r\n****** About to perform file read test... ******\r\n");
    res_sd = f_open(&fnew, "0:FatFs Read Write Test.txt", FA_OPEN_EXISTING | FA_READ);

    if(res_sd == FR_OK)
    {
        APP_PRINT("File opened successfully.\r\n");
        res_sd = f_read(&fnew, ReadBuffer, sizeof(ReadBuffer), &fnum);

        if(res_sd == FR_OK)
        {
            APP_PRINT("File read successful, bytes read:%d\r\n", fnum);
            APP_PRINT("Data read from the file:\r\n%s \r\n", ReadBuffer);
        }
        else
        {
            APP_PRINT("File read failed:(%d)\n", res_sd);
        }
    }
    else
    {
        APP_PRINT("Failed to open the file.\r\n");
    }

    /* 不再读，关闭文件 */
    f_close(&fnew);

    /* 不再使用文件系统，取消挂载文件系统 */
    //f_mount(NULL, "0:", 1);

    APP_PRINT("****** Test completed ******\r\n");
}


